package camera;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

import se.lth.cs.realtime.PeriodicThread;
import camerainterfaces.MotionDetectorInterface;

/**
 * MotionDector is a class which periodically checks a Axis camera for motion
 * and notifies the client. The message is sent over TCP/IP socket.
 */
public class MotionDetector extends PeriodicThread {
	private Socket socket;
	private MotionDetectorInterface detector;
	private PrintWriter writer;
	private boolean inMotion;

	/**
	 * Constructs and initiates the output stream.
	 * 
	 * @param period
	 *            - the period
	 * @param socket
	 *            - the socket which messages are sent over
	 */
	public MotionDetector(long period, Socket socket,
			MotionDetectorInterface detector) {
		super(period);
		this.detector = detector;
		this.socket = socket;
		try {
			writer = new PrintWriter(socket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		inMotion = false;
	}

	/**
	 * Called at the given period. Checks whether a motion happened or not and
	 * sends the message.
	 */
	@Override
	public void perform() {
		if (detector.detect() && !inMotion) {
			inMotion = true;
			writer.write("MOTION\n");
			writer.flush();

		} else if (!detector.detect() && inMotion) {
			inMotion = false;
			writer.write("NOMOTION\n");
			writer.flush();
		}
	}
}
